package com.zz.framework.core.ext

import android.app.Application
import com.zz.framework.core.BaseApp

fun Any?.toString(): String {
    if (this == null) return ""
    return toString()
}

fun Any?.getNonNullString(default: String = ""): String {
    if (this == null) return default
    return toString()
}

fun Long?.getNonNullLong(): Long {
    if (this == null) return 0
    return this
}

fun Long?.add(value: Long): Long {
    return if (this == null) {
        1
    } else {
        this + value
    }
}

fun Int?.getNonNullInt(): Int {
    if (this == null) return 0
    return this
}

fun Int?.add(value: Int): Int {
    return if (this == null) {
        1
    } else {
        this + value
    }
}

fun Double?.getNonNullDouble(): Double {
    if (this == null) return 0.0
    return this
}

fun Boolean?.getNonNullBoolean(): Boolean {
    if (this == null) return false
    return this
}

fun Int?.reduce(value: Int): Int {
    return if (this == null) {
        -1
    } else {
        this - value
    }
}

fun Long?.getNonNullValue(): Long {
    if (this == null) return 0
    return this
}


fun getAppVersion(): String {
    return runCatching {
        BaseApp.context.packageManager.getPackageInfo(BaseApp.context.packageName, 0).versionName
    }.getOrElse { "1.0" }.orEmpty()
}


fun getAppVersionCode(): Int {
    return runCatching {
        BaseApp.context.packageManager.getPackageInfo(BaseApp.context.packageName, 0).versionCode
    }.getOrElse { 1 }
}


fun Int.dp2px(): Int {
    val scale = BaseApp.context.resources.displayMetrics.density
    return (toFloat() * scale + 0.5f).toInt()
}
fun Int.dp(): Int {
    val scale = BaseApp.context.resources.displayMetrics.density
    return (toFloat() * scale + 0.5f).toInt()
}

fun Int.px2dp(): Int {
    val scale = BaseApp.context.resources.displayMetrics.density
    return (toFloat() / scale + 0.5f).toInt()
}

fun Int.sp2px(): Int {
    return (toFloat() * BaseApp.context.resources.displayMetrics.scaledDensity + 0.5f).toInt()
}

fun Int.px2sp(): Int {
    return (toFloat() / BaseApp.context.resources.displayMetrics.scaledDensity + 0.5f).toInt()
}


fun Float.dp(): Float {
    val scale = BaseApp.context.resources.displayMetrics.density
    return (this * scale + 0.5f)
}

fun Float.dp2px(): Int {
    return (this * BaseApp.context.resources.displayMetrics.density + 0.5f).toInt()
}

fun Float.px2dp(): Int {
    return (this / BaseApp.context.resources.displayMetrics.density + 0.5f).toInt()
}

fun Float.sp2px(): Int {
    return (this * BaseApp.context.resources.displayMetrics.scaledDensity + 0.5f).toInt()
}

fun Float.px2sp(): Int {
    return (this / BaseApp.context.resources.displayMetrics.scaledDensity + 0.5f).toInt()
}


